package com.gxlu.ms.base.result;

import java.util.ArrayList;
import java.util.List;

import com.gxlu.ms.base.util.JsonUtil;

/**
 * 分页结果集
 * @author andy.lhc
 * @date 2018/3/23
 */
public class PageQueryResult<T> extends Result<List<T>> {

    /**
     * 当前页
     */
    private int pageNum;

    /**
     * 总条数
     */
    private int totalCount;

    /**
     * 每页多少条
     */
    private int pageSize = 20;

    /**
     * 总页数
     */
    private int totalPage ;

    public PageQueryResult(){
    }

    public PageQueryResult(int pageNum, int totalCount){
        this.pageNum = pageNum;
        this.totalCount = totalCount ;
    }

    public PageQueryResult(int pageNum, int totalCount, int pageSize){
        this.pageNum = pageNum;
        this.totalCount = totalCount ;
        this.pageSize = pageSize;
        this.setCode(1);
    }

    public static  PageQueryResult success(){
        PageQueryResult result = new PageQueryResult();
        result.setStatus(true);
        result.setCode(1);
        return result;
    }

    public  PageQueryResult success(List<T> data) {
        PageQueryResult pageQueryResult = new PageQueryResult();
        pageQueryResult.setData(data);
        pageQueryResult.setStatus(true);
        pageQueryResult.setCode(1);
        return pageQueryResult;
    }

    public static PageQueryResult fail(int errorCode,
                                                 String errorMessage) {
        PageQueryResult result = new PageQueryResult();
        result.setStatus(false);
        result.setCode(errorCode);
        result.setMsg(errorMessage);
        result.setData(new ArrayList());
        return result;
    }

    public PageQueryResult<T> fail(String errorMessage) {
        return fail(0, errorMessage);
    }


    public int getPageNum() {
        return pageNum < 1 ? 1 : pageNum ;
    }

    public void setPageNum(int pageNum) {
        this.pageNum = pageNum;
    }

    public int getTotalCount() {
        return totalCount;
    }

    public void setTotalCount(int totalCount) {
        this.totalCount = totalCount;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    private int getCurrentPage() {
        return pageNum < 1 ? 1 : pageNum;
    }

    public boolean hasNext() {
        int useCount = (getCurrentPage() - 1) * getPageSize() + getSize();
        return totalCount > useCount;
    }

    public int getTotalPage() {
        if (pageSize == 0) {
            return 0;
        }
        return ((totalCount - 1) / pageSize) + 1;
    }

    private int getSize() {
        List<T> page = getData();
        if (page == null) {
            return 0;
        } else {
            return page.size();
        }
    }

    @Override
    public String toString() {
        return JsonUtil.toJson(this);
    }
}
